package com.kuang.lock8;

import javax.swing.plaf.synth.SynthCheckBoxMenuItemUI;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 实现Runnable接口，重写run方法
 *
 * Java多线程实现-Runnable接口 http://t.csdn.cn/pJhXV
 */
class Person implements Runnable {

    private String id;
    private String name;
    private String loginType;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLoginType() {
        return loginType;
    }

    public void setLoginType(String loginType) {
        this.loginType = loginType;
    }

    @Override
    public void run() {
        // 类锁，锁类的Class对象（模板）
        synchronized (Person.class){
            for (int i = 0; i < 1000; i++) {
                System.out.println(Thread.currentThread().getName()+"===========");
            }
        }
        // for循环放在锁外面，线程之间就需要加睡眠，否则会出现CPU多次切换线程的情况
        //synchronized (Person.class){
        //    System.out.println(Thread.currentThread().getName()+"===========");
        //}
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null){
            return false;
        }
        if (obj == this || getClass() == obj.getClass()){
            return true;
        }
        if (obj instanceof Person){
            Person person = (Person) obj;
            return this.id.equals(person.getId()) && this.name.equals(person.getName());
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id,name);
    }

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", loginType='" + loginType + '\'' +
                '}';
    }

    public static void main(String[] args) {
        Person personA = new Person();
        Person personB = new Person();
        new Thread(personA).start();
        new Thread(personB).start();


        //for循环放在锁外面，线程之间就需要加睡眠，否则会出现CPU多次切换线程的情况
        //new Thread(()->{
        //    for (int i = 0; i < 1000; i++) {
        //        personA.run();
        //    }
        //}).start();
        //try {
        //    TimeUnit.SECONDS.sleep(1);
        //} catch (InterruptedException e) {
        //    e.printStackTrace();
        //}
        //new Thread(()->{
        //    for (int i = 0; i < 1000; i++) {
        //        personB.run();
        //    }
        //}).start();
    }
}
